package com.fast.linkbeanadmin.security.impl;

import cn.hutool.core.convert.Convert;
import com.fast.linkbeanadmin.constants.CacheConstants;
import com.fast.linkbeanadmin.pojo.dto.SecurityUserDTO;
import com.fast.linkbeanadmin.pojo.dto.TokenDTO;
import com.fast.linkbeanadmin.pojo.response.ResultBean;
import com.fast.linkbeanadmin.pojo.vo.login.LoginResultVO;
import com.fast.linkbeanadmin.utils.jwt.JwtUtil;
import com.fast.linkbeanadmin.utils.redis.RedisUtil;
import com.fast.linkbeanadmin.utils.response.ResponseUtil;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author ruan cai yuan
 * @version 1.0
 * @fileName com.fast.linkbeanadmin.security.impl.AuthenticationSuccessHandlerImpl
 * @description: 登录成功的拦截器
 * @since 2024/7/21 下午5:49
 */
@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
    @Resource
    private RedisUtil redisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //1.生成token  2.用户信息级存到redis  3.返回到客户端
        Object principal = authentication.getPrincipal();
        if (principal instanceof SecurityUserDTO) {
            SecurityUserDTO dto = (SecurityUserDTO) principal;
            // 生成token
            TokenDTO tokenDTO = new TokenDTO();
            tokenDTO.setId(dto.getUserDO().getId());
            tokenDTO.setUsername(dto.getUsername());
            tokenDTO.setAvatarPath(dto.getUserDO().getAvatar());
            String token = JwtUtil.getToken(tokenDTO);
            // 用户信息缓存到redis中[24小时过期]
            redisUtil.set(CacheConstants.LOGIN_USERNAME_KEY + dto.getUsername(), dto, 24, TimeUnit.HOURS);
            // 返回到客户端
            LoginResultVO loginResultVo = Convert.convert(LoginResultVO.class, dto);
            loginResultVo.setToken(token);
            ResultBean loginSuccess = ResultBean.success(loginResultVo);
            ResponseUtil.responseData(response, loginSuccess, MediaType.APPLICATION_JSON_VALUE);
        }

    }
}
